package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.constant.RedisConstants;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 * CacheUtils
 * </p>
 *
 * @author flyduck
 * @since 2025/3/11
 */
@Slf4j
@Component
public class CacheUtils {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, Object value, long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWithLogicalExpire(String key, Object value, long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public  <R,ID> R queryWithPassThrough(String keyPrefix,
                                          ID id,
                                          Class<R> clazz,
                                          Function<ID,R> function,
                                          long time,
                                          TimeUnit unit){
        //从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);

        //存在直接返回
        if (json != null) {
            if (StrUtil.isNotBlank(json)) {
                R r = JSONUtil.toBean(json, clazz);
                return r;
            }else {
                //店铺在数据库不存在，缓存了 ""
                return null;
            }
        }

        //根据id查询数据库
        R r = function.apply(id);

        //不存在，返回错误
        if (r == null) {
            stringRedisTemplate.opsForValue().set(keyPrefix + id, "",
                    RedisConstants.RedisCommonConstants.CACHE_NULL_TTL,
                    TimeUnit.MINUTES);
            return null;
        }

        //把数据写入redis
        set(keyPrefix+id, r, time, unit);

        return r;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key,
                "1",
                RedisConstants.RedisShopConstants.LOCK_SHOP_TTL,
                TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 根据id查询商铺信息-逻辑过期解决缓存击穿问题(不需要考虑缓存穿透问题，所以不用缓存NULL值了，因为热key来自于缓存预热ApplicationInit)
     * @param id
     * @return
     */
    public  <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id,
                                            Class<R> clazz,
                                            String lockKeyPrefix,
                                            Function<ID,R> function,
                                            long time,
                                            TimeUnit unit){
        //从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);

        //不存在直接NULL
        if (StrUtil.isBlank(json)) {
            return null;
        }

        //未过期，直接返回店铺信息
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        R oldR = JSONUtil.toBean((JSONObject) redisData.getData(),clazz);
        if(expireTime.isAfter(LocalDateTime.now())){
            return oldR;
        }

        //已过期，开始缓存重建
        //1、获取互斥锁
        boolean obtainLockFlag = tryLock(lockKeyPrefix + id);

        //2、获取互斥锁失败：返回过期店铺信息
        if (!obtainLockFlag) {
            return oldR;
        }

        //3、获取锁成功：Double Check
        String jsonStr = stringRedisTemplate.opsForValue().get(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id);
        if (StrUtil.isNotBlank(jsonStr)) {
            RedisData redisDataObject = JSONUtil.toBean(jsonStr, RedisData.class);
            if(redisDataObject.getExpireTime().isAfter(LocalDateTime.now())){
                return JSONUtil.toBean((JSONObject) redisDataObject.getData(), clazz);
            }
        }

        //4、获取互斥锁成功：开启独立线程实现缓存重建
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try {
                //从数据库查询对象
                R r = function.apply(id);
                //写入redis
                setWithLogicalExpire(keyPrefix + id, r, time, unit);
            } finally {
                //释放锁
                unlock(RedisConstants.RedisShopConstants.LOCK_SHOP_KEY_PREFIX + id);
            }

        });
        return oldR;
    }


}
